﻿using MiniFox.Components;
using MiniFox.Data.EntityFramework;
using MiniFox.Platform.Applications.Models;
using MiniFox.Platform.Applications.Providers;
using MiniFox.Utility;

namespace Platform.Data
{
    /// <summary>
    /// 
    /// </summary>
    [AutoResolve]
    public class PlatformProvider : EntityDataProvider<PlatformDbContext>, IPlatformProvider
    {
        public SystemGlobalConfig GetEnvironmentConfig()
        {
            var sysEnv = this.CurrentDbContext.SysEnvConfig.FirstOrDefault();
            if (sysEnv == null) return null;

            var envConfig = sysEnv.ConfigData.ToJsonObject<EnvConfig>();
            return new SystemGlobalConfig
            {
                BuiltinUrls = envConfig.BuiltinUrls,
                CopyRight = envConfig.CopyRight,
                DefaultApplicationID = envConfig.DefaultApplicationID,
                Description = envConfig.Description,
                HomeUri = envConfig.HomeUri,
                LogoUri = $"/file/load/sys?fileId={envConfig.Logo}",
                IconUri = $"/file/load/sys?fileId={envConfig.Icon}",
                ICP = envConfig.ICP,
                Title = envConfig.Title,
                Theme = envConfig.Theme,
                WarningUri = envConfig.WarningUri
            };
        }

        public Organization GetOrganization(string orgId)
        {
            var org = this.CurrentDbContext.SysOrganization.SingleOrDefault(o => o.OrgId == orgId);
            if (org == null)
                return null;
            return new Organization
            {
                ID = org.OrgId,
                Name = org.OrgName,
                DisplayName = org.DisplayName,
                Description = org.Description,
                Icon = org.Icon,
                //DefaultTheme = org.DefaultTheme,
                Logo = org.Logo
            };
        }

        public SystemNavModuleEntry[] GetSystemModules()
        {
            var modules = (from m in this.CurrentDbContext.SysModule
                           join a in this.CurrentDbContext.SysApp on m.AppId equals a.AppId
                           where m.Enabled == true
                           select new SystemNavModuleEntry
                           {
                               ApplicationID = m.AppId,
                               RequireSSL = a.Ssl,
                               Host = a.Host ?? "localhost",
                               Port = a.Port,
                               RootPath = a.Path,
                               ID = m.ModuleId,
                               Name = m.ModuleName,
                               Url = m.ModuleUri,
                               Icon = m.Icon,
                               QueryString = m.QueryString,
                               IsPublic = m.IsPublic

                           }).ToArray();
            return modules ?? null;
        }
    }
}
